//
//  DownloadTask.h
//  DownloadManagerDemo
//
//  Created by ejiang on 2021/12/9.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

typedef enum : NSUInteger {
    /// 未知
    DownloadTaskStatusUnknown               = 0,
    /// 等待中
    DownloadTaskStatusWaiting,
    /// 下载中
    DownloadTaskStatusDownloading,
    /// 下载完成，还没有从tmp移动到目标文件夹的阶段
    DownloadTaskStatusMoving,
    /// 完成
    DownloadTaskStatusFinish,
    /// 发生错误
    DownloadTaskStatusError,
    /// 用户暂停
    DownloadTaskStatusPause,
} DownloadTaskStatus;

@interface Speed : NSObject

/// 上一个didWriteData回调的时间
@property (nonatomic, strong, nullable) NSDate * oldDate;

/// 下载速率
@property (nonatomic, assign) int64_t speedBytes;

@end

@interface FileInfo : NSObject

/// 已经下载的bytes
@property (nonatomic, assign) int64_t totalBytesWritten;

/// 文件总bytes，可能不准
@property (nonatomic, assign) int64_t totalBytesExpectedToWrite;

@end

static NSString * const kFileHandleError = @"FileHandle.Error";
static NSString * const kServerError = @"Server.Error";

typedef enum : NSUInteger {
    FileHandleErrorTargetNotExist             = 0,
    FileHandleErrorMoveFail,
} FileHandleError;

//@interface DownloadError : NSObject
//
//@property (nonatomic, assign) NSInteger code;
//
//@property (nonatomic, strong) NSString * errorMessage;
//
//+ (instancetype)errorWithDomain:(NSString *)domain code:(NSInteger)code errorMessage:(NSString *)errorMessage;
//
//@end

/// 下载任务
@interface DownloadTask : NSObject

/// 主键
@property (nonatomic, copy) NSString * taskId;

/// 任务状态
@property (nonatomic, assign) DownloadTaskStatus status;

/// 存储到本地的名称，带扩展名
@property (nonatomic, copy) NSString * targetName;

/// 下载链接
@property (nonatomic, copy) NSString * downloadPath;

/// Document下的相对文件夹路径
@property (nonatomic, copy) NSString * targetDir;

/// 下载任务信息，从回调获取到的文件信息
@property (nonatomic, strong) FileInfo * info;

/// 下载速率
@property (nonatomic, strong) Speed * speed;

/// 错误
@property (nonatomic, strong, nullable) NSDictionary * errorDic;

/// 扩展字段，存储差异化信息
@property (nonatomic, strong) NSDictionary * extInfo;

/// 初始化
/// @param downloadPath 下载链接
/// @param targetName 存储到本地的名称，带扩展名 可不传，使用下载链接中的名字, 如果存在同名文件会自动重命名
/// @param targetDir 目标目录，Document文件夹下的相对文件夹路径，不传为Document根目录，传了就是Document子文件夹
- (instancetype)initWithDownloadPath:(NSString *)downloadPath targetName:(NSString * __nullable)targetName targetDir:(NSString *__nullable)targetDir;

- (BOOL)moveTmpToTarget:(NSURL *)tmpURL;

- (void)saveTmpResumeData:(NSData *)resumeData;
- (NSData *__nullable)tmpResumeData;

- (void)reInit;
- (void)removeLocal;

@end

NS_ASSUME_NONNULL_END
